import store from '@/store/index.js'
import { create, pay, get_openid } from '@/api/user.js'
export default {
	methods: {
		// 获取openid
		get_openid(orderNo, dl) {
			uni.login({
				success: (res) => {
					if (res.errMsg == 'login:ok') {
						get_openid({ code: res.code }).then(res => {
							console.log(res)
							if (res.code == 1) {
								this.pay(orderNo, res.data.openid, dl)
							}
						})
					}
				},
				fail: (res) => {
					console.log(res)
				}
			})
		},
		// 发起支付
		pay(orderNo, openid, dl) {
			let obj = {
				dl,
				order_no: orderNo,
				openid
			}
			pay(obj).then(res => {
				console.log(res)
				if (res.code == 1) {
					this.wx_pay(res.data)
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				}
			})
		},
		// 调起微信支付
		wx_pay(data) {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: (res) => {
					if (res.errMsg == 'requestPayment:ok') {
						let ids = []
						store.state.common.msg.forEach(item => {
							if (item.message_type == 1 || item.message_type == 2) {
								ids.push(item.masterplate)
							}
						})
						// #ifdef MP-WEIXIN
						wx.requestSubscribeMessage({
							tmplIds: ids,
							success: (res) => {
								console.log(res)
							},
							fail: (res) => {
								console.log(res)
							},
							complete: () => {
								uni.redirectTo({
									url: '/pages/order/order?index=2'
								})
							}
						})
						// wx.getSetting({
						// 	withSubscriptions: true,
						// 	success: (res) => {
						// 		console.log(res)
						// 		if (!res.subscriptionsSetting.mainSwitch) {

						// 		} else {
						// 			uni.redirectTo({
						// 				url: '/pages/order/order?index=2'
						// 			})
						// 		}
						// 	}
						// })
						// #endif
						// #ifdef H5
						uni.redirectTo({
							url: '/pages/order/order?index=2'
						})
						// #endif

					}

				},
				fail: (res) => {
					// 支付失败跳转待付款订单页
					uni.redirectTo({
						url: '/pages/order/order?index=1'
					})
				},
				complete: () => {
					store.commit('set_yhq_msg', '')
				}
			})
		}
	},
}